/**
 * 工作线程计算结果并放入发送队列
 * */
import java.net.DatagramPacket;
import java.net.InetAddress;

public class CalculateThread extends Thread{

    private synchronized  static int calculate(int a, int b, char op){
        int result;
        if (op == '+') {
            result = a + b;
            Server.add_count++;
        } else if (op == '-') {
            result = a - b;
            Server.sub_count++;
        } else if (op == '*') {
            result = a * b;
            Server.mul_count++;
        } else {
            result = a / b;
            Server.div_count++;
        }
        System.out.println("加法目前成功处理了："+Server.add_count+"次");
        System.out.println("减法目前成功处理了："+Server.sub_count+"次");
        System.out.println("乘法目前成功处理了："+Server.mul_count+"次");
        System.out.println("除法目前成功处理了："+Server.div_count+"次");
        return result;
    }

    public void run(){
        try {
            while (true) {
                Thread.sleep(500);
                DatagramPacket receivePacket = Server.receiveQueue.take();
                InetAddress client_address = receivePacket.getAddress();
                int client_port = receivePacket.getPort();
                DatagramPacket resultPacket;
                String expression = new String(receivePacket.getData());
                int index1, index2;
                index1 = expression.indexOf(' ');
                index2 = expression.indexOf(' ', index1 + 1);
                char op = expression.charAt(0);//不包括end
                String s1 = expression.substring(index1 + 1, index2);
                String s2 = expression.substring(index2 + 1).trim();//去除空格
                System.out.println("开始计算：" + s1 + op + s2);
                int a = Integer.parseInt(s1);
                int b = Integer.parseInt(s2);
                int result=calculate(a, b, op);//计算部分使用syn加锁，更新全局变量
                System.out.println("result=" + result + "   现在准备把结果返回给客户端");
                byte[] b_result = String.valueOf(result).getBytes();
                resultPacket = new DatagramPacket(b_result, b_result.length, client_address, client_port);
                Server.sendQueue.add(resultPacket);//线程满就会阻塞
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
